#include <Arduino.h>
#include "display.h"
#include "imu.h"
#include "ambient.h"
#include "network.h"
#include "sd_card.h"
#include "rgb_led.h"
#include "lv_port_indev.h"
#include "lv_cubic_gui.h"
//#include "lv_bilifens.h"
#include "lv_demo_encoder.h"


/*** Component objects ***/
Display screen;
IMU mpu;
Pixel rgb;
Ambient ambLight;
SdCard tf;
Network wifi;
extern EspClass ESP;

int fans;
int tian;
long time1;

String  appid = "55551439";		     //天气API应用APPID	  账号注册申请地址https://www.tianqiapi.com
String  appsecret = "NEk0V71b";		 //天气API应用APPSecret
String  cityid = "101010100";		 //天气API城市ID 北京
String  biliid = "30422178";		 //Bilibili账号ID
String  biliname = "BiliBili";		 //BiliBili昵称
String  cityname = "Xi'an";		 //城市名

String ssid = "ssid";
String password = "password";

int flag = 0;
float fade = 0;
extern int action_direction;
int page = 0;
long previousMillis = 0;
long interval = 1800000;
float brightness = 0.5;

bool wifiInited = false;
bool page5_inited = false;

int time_sec = 0,time_min = 0;

void wifiRefresh() {
	if (millis() - previousMillis >= interval) 
	{
		previousMillis = millis();
	}
	else if (wifiInited || wifi.isConnected()) {
		return;
	}
	/*** Read WiFi info in SD-Card, then scan & connect WiFi ***/
	if (!wifiInited) {
		wifiInited = true;
		wifi.init(ssid, password);
	}
	if (wifi.isConnected()) {

		rgb.setBrightness(0.1).setRGB(210, 32, 32);
		fans = wifi.getBilibiliFans("http://api.bilibili.com/x/relation/stat?vmid="+biliid);
		Serial.println(fans);
		tian = wifi.getTianqi("https://www.tianqiapi.com/api?version=v6&appid="+appid+"&appsecret="+appsecret+"&cityid="+cityid);
		Serial.println(tian);

		char fengs[8];
		char tiangqi[8];
		char cityname1[10];
		itoa(fans, fengs, 10);
		itoa(tian, tiangqi, 10);
		const char* fens = fengs;
		const char* tianq = tiangqi;
		const char* cityname2 = strcpy(cityname1,cityname.c_str());

		if (page != 5) {
			lv_holo_cubic_gui(tianq,fens,cityname2,ESP.getFreeHeap());
		}
		rgb.setBrightness(0.1).setRGB(0, 122, 204);

		screen.SyncTime();
		page5_inited = false;
	} else {
		wifiInited = false;
	}
}

void setup()
{
	Serial.begin(115200);

	delay(500);
	Serial.println("Starting!");

	/*** Init screen ***/
	screen.init();
	screen.setBackLight(1.0f);
	Serial.println("Screen Inited!");

	lv_holo_cubic_gui("--", "0", "--", 0);
	lv_scr_load_anim(scr5, LV_SCR_LOAD_ANIM_NONE, 500, 500, false);

	page = 5;

	action_direction = 0;
	Serial.println("UI Inited!");

	/*** Init IMU as input device ***/
	lv_port_indev_init();
	Serial.println("lv_port_indev_init Inited!");
	mpu.init();
	Serial.println("MPU Inited!");

	/*** Init on-board RGB ***/
	rgb.init();
	rgb.setBrightness(0.5).setRGB(0, 122, 204);
	Serial.println("RGB Inited!");

	/*** Init ambient-light sensor ***/
	// ambLight.init(ONE_TIME_H_RESOLUTION_MODE);

	/*** Init micro SD-Card ***/
#if 1
	tf.init();
	Serial.println("TF Inited!");

	String tf_ssid = tf.readFileLine("/wifi.txt", 1);		// line-1 for WiFi ssid
	String tf_password = tf.readFileLine("/wifi.txt", 2);	// line-2 for WiFi password
	String tf_cityId = tf.readFileLine("/wifi.txt", 3);		// line-3 for Cityname
	String tf_cityname = tf.readFileLine("/wifi.txt", 4);		// line-3 for Cityname
	String tf_bilibiliId = tf.readFileLine("/wifi.txt", 5);	// line-4 for BiliBiliId
	String tf_bilibiliName = tf.readFileLine("/wifi.txt", 6);	// line-4 for BiliBiliId
	String tf_weatherAppId = tf.readFileLine("/wifi.txt", 7);	// line-5 for weatherAppId
	String tf_weatherAppSecret = tf.readFileLine("/wifi.txt", 8);	// line-6 for BiliBiliId
	Serial.printf("tf_ssid %s\r\n", tf_ssid.c_str());
	Serial.printf("tf_password %s\r\n", tf_password.c_str());
	Serial.printf("tf_cityId %s\r\n", tf_cityId.c_str());
	Serial.printf("tf_cityname %s\r\n", tf_cityname.c_str());
	Serial.printf("tf_bilibiliId %s\r\n", tf_bilibiliId.c_str());
	Serial.printf("tf_bilibiliName %s\r\n", tf_bilibiliName.c_str());
	Serial.printf("tf_weatherAppId %s\r\n", tf_weatherAppId.c_str());
	Serial.printf("tf_weatherAppSecret %s\r\n", tf_weatherAppSecret.c_str());

	ssid = tf_ssid;
	password = tf_password;
	appid = tf_weatherAppId;
	appsecret = tf_weatherAppSecret;
	cityid = tf_cityId;
	cityname = tf_cityname; 
	biliid = tf_bilibiliId;
	biliname = tf_bilibiliName;
#endif

	/***  以下两句只能二选一  ***/
/***    使用WIFI默认配网取消注释此句    ***/
    //while(  screen.PreWIFIConnect(wife_ssid, wife_pass)   );
    // screen.ShowERWEIMA();
/***  使用微信小程序自动配网取消注释此句  ***/
	// while(  screen.PreWebConnect("WIFI-WEB")   );

	/*** Inflate GUI objects ***/
	// lv_demo_benchmark();
	// lv_demo_encoder();
	//tf.readBinFromSd("/ali.bin", (uint8_t*)screen_buffer.data);
	//tf.writeBinToSd("/ali.bin", (uint8_t*)screen_buffer.data + 64);
	
	wifiRefresh();
	//lv_scr_load_anim(scr2, LV_SCR_LOAD_ANIM_MOVE_LEFT, 500, 3000, false);

	/*tf.listDir("/", 0);
	tf.createDir("/mydir");
	tf.listDir("/", 0);
	tf.removeDir("/mydir");
	tf.listDir("/", 2);
	tf.writeFile("/hello.txt", "Hello ");
	tf.appendFile("/hello.txt", "World!\n");
	tf.readFile("/hello.txt");
	tf.deleteFile("/foo.txt");
	tf.renameFile("/hello.txt", "/foo.txt");
	tf.readFile("/foo.txt");
	tf.fileIO("/test.txt");
	Serial.printf("Total space: %lluMB\n", SD.totalBytes() / (1024 * 1024));
	Serial.printf("Used space: %lluMB\n", SD.usedBytes() / (1024 * 1024));*/


	//Serial.println(sizeof(screen_buffer));

	time1 = millis();
	
}

void loop()
{
	// run this as often as possible 
	screen.routine();

	mpu.update(200);

	wifiRefresh();

	// Serial.print("scr count: "); Serial.println(scrs_count);

	// rgb.setBrightness(ambLight.getLux() / 500.0);
	// Serial.println(ambLight.getLux());

	delay(10);

	//if (Serial.available() > 0)
	//{
	//	char c = Serial.read();
	//	//lv_scr_load_anim(scr2, LV_SCR_LOAD_ANIM_FADE_ON, 300, 500, false);
	//}


	lv_obj_t* current = scrs[page];
	lv_obj_t* target = NULL;
	if (action_direction == 1) {
		page5_inited = false;
		page --;
		if (page < 0) page = scrs_count - 1;
		target = scrs[page];
		time1 = millis();
		flag = 1;
	}
	else if (action_direction == 2) {
		page5_inited = false;
		page ++;
		if (page >= scrs_count) page = 0;
		target = scrs[page];
		time1 = millis();
		flag = 1;
	}
	else {
		flag = 0;
	}

	if (action_direction && target) {
		rgb.setBrightness(0.1).setRGB(65, 120, 32);
		lv_scr_load_anim( 
			target, 
			action_direction > 1 ? LV_SCR_LOAD_ANIM_MOVE_LEFT : LV_SCR_LOAD_ANIM_MOVE_RIGHT, 500, 500, false);
		action_direction = 0;
		time1 = millis();
	} else {
		rgb.setBrightness(0.1).setRGB(0, 122, 204);
	}

	if (action_direction == 0 && page == 3) {
		// time1 = millis();
		showTimeUI();
	}
	if (action_direction == 0 && page == 4) {
		// time1 = millis();
		screen.showClock();
	}
	if (action_direction == 0 && page == 5) {
		// time1 = millis();
		if (page5_inited) {
			screen.digitalClockDisplay(cityid);
		}
		if (!page5_inited) {
			page5_inited = true;
			screen.digitalClockDisplayInit(cityid);
		}
	}


	// if (millis() - time1 > 5000 && !flag)
	// {
	// 	flag = 1;
	// 	lv_scr_load_anim(scr1, LV_SCR_LOAD_ANIM_NONE, 10, 0, false);
	// 	page = 0;
	// }


	// delay(500);
}

void showTimeUI() {
	if (millis() - time1 > 1000)
	{
		time1 = millis();
        time_sec += 1;
        if(time_sec == 30)
        {
            time_sec = 0;
			time_min +=1;
        }    
            
        if (timeStatus() != timeNotSet) 
            screen.ShowTime(0);
        
        if(time_min == 2)
        {
            screen.SyncTime();
        }
    }
}